package com.hpc.Controller;

import Utils.JSONUtil;
import Utils.JWTUtil;
import Utils.ResultUtil;
import Utils.wordsFilterUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hpc.VO.msgVo;
import entity.ResultEnum;
import entity.systemConstant;
import entity.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ts/user")
public class userController1 {
    @Autowired
    private com.hpc.Service.userService userService;
    @Resource
    private com.hpc.Service.adminService adminService;
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * @author: Liujd
     * @createTime: 2023/4/16 21:25
     * @description: login登录
     * @param:[username账号, password密码]
     * @return:java.lang.String
     */
    @PostMapping("/login")
    public String login(String username,String password){
        user login = userService.login(username, password);
        if (login!=null){
            if(login.getUseStatus().equalsIgnoreCase("1")){
                String gettoken = JWTUtil.gettoken(login);
                //登录成功设置token时长30分钟
                redisTemplate.opsForValue().set(login.getSerial(),gettoken,30, TimeUnit.MINUTES);
                HashMap<String,String> map = new HashMap<>();
                map.put("token",gettoken);
                map.put("userInfo",JSONUtil.toJSONString(login));
                return JSONUtil.toJSONString(ResultUtil.success(map));
            }else {
                return JSONUtil.toJSONString(ResultUtil.error("对不起，您的账号已被封禁，请联系管理员！"));
            }
        }
        return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));
    }
    /**
     * @author: Liujd
     * @createTime: 2023/5/17 18:05
     * @description: follow对指定用户进行关注
     * @param:[userId, followerId]
     * @return:java.lang.String
     */
    @GetMapping("/follow")
    public String follow(String userId,String followerId){
        String keyName=followerId+"_follow";
        Long opsResult1;
        Long opsResult2=0L;
        try {
            opsResult1 = redisTemplate.opsForList().rightPush(keyName, userId);
            //向redis更新数据，标记该用户存在关注者，用于博主发新文 定向消息通知
            opsResult2 = redisTemplate.opsForList().rightPush(systemConstant.USERS_HASFOLLOWS, keyName);
        }catch (Exception e){
            e.printStackTrace();
            opsResult1=0L;
        }
        if (opsResult1==0&opsResult2==0){
            return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));

        }else {
            return JSONUtil.toJSONString(ResultUtil.success("关注成功"));
        }
    }
    @GetMapping("/unfollow")
    public String unfollow(String userId,String followerId){
        String keyName=followerId+"_follow";
        Long opsResult;
        try {
            opsResult = redisTemplate.opsForList().remove(keyName, 1, userId);
        }catch (Exception e){
            e.printStackTrace();
            opsResult=0L;
        }
        if (opsResult==0){
            return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));
        }else {
            return JSONUtil.toJSONString(ResultUtil.success("取消关注成功"));
        }
    }
    @GetMapping("/myfollowers")
    public String myfollowers(String userId){
        try {
            String keyName=userId+"_follow";
            if (redisTemplate.hasKey(keyName)) {
                List<String> followers = redisTemplate.opsForList().range(keyName, 0, -1);
                if (followers.size()!=0) {
                    List<user> getfollowers = userService.getfollowers(followers);
                    return JSONUtil.toJSONString(ResultUtil.success(getfollowers));
                }else {
                    return JSONUtil.toJSONString(ResultUtil.success());
                }
            }else {
               return  JSONUtil.toJSONString(ResultUtil.success());
            }
        }catch (Exception e){
            e.printStackTrace();
            return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));
        }

    }
    @PostMapping("/changeheadsculpture")
    public String changeheadsculpture(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return JSONUtil.toJSONString(ResultUtil.error("请选择要上传的文件"));
        }
        String extension = getFileExtension(file.getOriginalFilename());
        String newFilename = "user-" + UUID.randomUUID() + "." + extension;

        try {
            String imagesDirPath = "/bishe/TS/images/";//服务器图片保存目录
            File imagesDir = new File(imagesDirPath);
            if (!imagesDir.exists()) {
                imagesDir.mkdirs();
            }

            String filePath = imagesDirPath + newFilename;
            File dest = new File(filePath);
            file.transferTo(dest);

            // 获取本机IP地址
//            InetAddress address = InetAddress.getLocalHost();
//            String host = address.getHostAddress();
            String ip="localhost";
            String port="8080";

            // 构造图片URL并返回
            String imageUrl = "http://" + ip + ":" + port + "/api/get-image?filename=" + newFilename;
            return JSONUtil.toJSONString(ResultUtil.success(imageUrl));
        } catch (IOException e) {
            return JSONUtil.toJSONString(ResultUtil.error("图片上传失败！"+e.getMessage()));
        }
    }
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1);
    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request){
        String token = request.getHeader("token");
        DecodedJWT decodejwt = JWTUtil.decodejwt(token);
        String userid = decodejwt.getClaim("userid").asString();
        Boolean delete = redisTemplate.delete(userid);
        if (delete) {
            return JSONUtil.toJSONString(ResultUtil.success("退出登录成功"));
        }else {
            return JSONUtil.toJSONString(ResultUtil.error("退出登录失败！"));
        }
    }
    @PostMapping("/saveprofilechange")
    public String saveprofilechange(user user){
        int i = userService.modifyUserInfo(user);
        if (i==1){
            entity.user userInfo = userService.getUserInfoBySerial(user.getSerial());
            return JSONUtil.toJSONString(ResultUtil.success(userInfo));
        }else{
            return JSONUtil.toJSONString(ResultUtil.error(ResultEnum.ERROR));
        }

    }
    /**
     * @author : Liujd
     * @ClassName userController1
     * @Description 展示登陆者本人的个人主页，跟查看其他人的个人主页，所以该接口入参userId，
     * 返回用户实体类信息，跟对应的用户所有文章
     * @date : 22:40 2023/5/4
     * @Version
     **/
    @GetMapping("/personalHomePageRelated")
    public String personalHomePageRelated(String userId,HttpServletRequest request){
        String token = request.getHeader("token");
        DecodedJWT decodejwt = JWTUtil.decodejwt(token);
        String useridIntoken = decodejwt.getClaim("userid").asString();
        return JSONUtil.toJSONString(ResultUtil.success(userService.personalHomePageRelated(userId,useridIntoken)));
    }
    @GetMapping("/getmsg")
    public String msgOfUser(String userId){
        List<msgVo> msgVos = userService.msgsOfUser(userId);
        return JSONUtil.toJSONString(ResultUtil.success(msgVos));
    }
    public String publishArticle(String[] imagesUrls,String content,String type){
        return "";
    }
    /**
     * @author : Liujd
     * @ClassName userController1
     * @Description 用户注册接口
     * @date : 16:11 2023/5/16
     * @Version
     **/
    @PostMapping("/register")
    public String register(user user){
        System.out.println(user.getPassword()+user.getUsername());
        int register = userService.register(user);
        if (register!=0){
            return JSONUtil.toJSONString(ResultUtil.success());
        }
        return JSONUtil.toJSONString(ResultUtil.error("账号已存在！"));
    }
    /**
     * @author: Liujd
     * @createTime: 2023/5/28 0:54
     * @description: messageOfTS 用户对系统的反馈
     * @param:[]
     * @return:java.lang.String
     */
    @PostMapping("/message")
    public String messageOfTS(HttpServletRequest request,String message){
        String s = wordsFilterUtil.wordsCheck(message);
        if (!s.isEmpty()){
            return JSONUtil.toJSONString(ResultUtil.error("您的留言内容存在敏感词汇："+s));
        }
        String token = request.getHeader("token");
        String userid = JWTUtil.decodejwt(token).getClaim("userid").asString();
        int i = userService.addMessage(userid, message);
        if (i!=0){
            Map<String, Object> allMessages = adminService.getAllMessages();
            return JSONUtil.toJSONString(ResultUtil.success(allMessages));
        }else {
            return JSONUtil.toJSONString(ResultUtil.error("留言失败！"));
        }
    }
    @GetMapping("/loginCheck")
    public String loginStatusCheck(HttpServletRequest request){
        String token="";
        try {
             token = request.getHeader("token");
        }catch (Exception e){
            e.printStackTrace();
        }
        if(!StringUtils.isEmpty(token)) {
            String userid = JWTUtil.decodejwt(token).getClaim("userid").asString();
            Boolean aBoolean = redisTemplate.hasKey(userid);

            if (aBoolean) {
                user userInfoBySerial = userService.getUserInfoBySerial(userid);
                return JSONUtil.toJSONString(ResultUtil.success(userInfoBySerial));
            } else {
                return JSONUtil.toJSONString(ResultUtil.error("您还未登录！"));
            }
        }else {
            return JSONUtil.toJSONString(ResultUtil.error("您还未登录！"));
        }
    }
}
